using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using RiceShop.Models;
using RiceShop.Services;
using System.Reflection; // 用于获取程序集信息
using System.Security.Claims;  // 用于JWT声明处理
using System.Text;






namespace RiceShop
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // 创建Web应用程序构建器
            var builder = WebApplication.CreateBuilder(args);

            // ========== 数据库配置 ==========
            // 配置Entity Framework数据库上下文，使用SQL Server
            builder.Services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

            // ========== Identity身份认证配置 ==========
            // 配置ASP.NET Core Identity用户管理系统
            builder.Services.AddIdentity<IdentityUser, IdentityRole>()
           .AddEntityFrameworkStores<ApplicationDbContext>() // 使用EF存储用户数据
           .AddDefaultTokenProviders(); // 添加默认令牌提供程序

            // ========== JWT认证配置 ==========
            // 获取JWT密钥，如果未配置则抛出异常
            var jwtKey = builder.Configuration["Jwt:Key"];
            if (string.IsNullOrEmpty(jwtKey))
            {
                throw new InvalidOperationException("JWT Key is not configured.");
            }

            // 配置JWT Bearer认证
            builder.Services.AddAuthentication(options =>
            {
                // 设置默认认证方案为JWT Bearer
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                // JWT令牌验证参数配置
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,          // 验证发行者
                    ValidateAudience = true,        // 验证受众
                    ValidateLifetime = true,        // 验证生命周期
                    ValidateIssuerSigningKey = true, // 验证签名密钥
                    ValidIssuer = builder.Configuration["Jwt:Issuer"],     // 有效发行者
                    ValidAudience = builder.Configuration["Jwt:Audience"], // 有效受众
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)), // 签名密钥
                    ClockSkew = TimeSpan.Zero,      // 消除默认的5分钟时间偏差容差
                    RequireExpirationTime = true    // 要求令牌必须有过期时间
                };

                // JWT Bearer事件处理
                options.Events = new JwtBearerEvents
                {
                    // 认证失败时的处理
                    OnAuthenticationFailed = context =>
                    {
                        // 如果是令牌过期异常，添加响应头标识
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Append("Token-Expired", "true");
                        }
                        return Task.CompletedTask;
                    }
                };
            });

            // ========== 控制器和JSON配置 ==========
            // 配置控制器和JSON序列化选项
            builder.Services.AddControllers()
                .AddJsonOptions(options =>
                {
                    // 忽略循环引用，防止序列化时出现死循环
                    options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
                });

            // ========== Swagger API文档配置 ==========
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen(c =>
            {
                // 配置Swagger文档信息
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "RiceShop API",
                    Version = "v1",
                    Description = "RiceShop 后台管理系统 API"
                });

                // 添加JWT Bearer认证到Swagger
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer"
                });

                // 为所有API操作添加安全要求
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                        Array.Empty<string>()
                    }
                });

                // 添加XML注释文档支持
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                if (File.Exists(xmlPath))
                {
                    c.IncludeXmlComments(xmlPath);
                }
            });



            // ========== CORS跨域配置 ==========
            // 配置跨域资源共享策略
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                    builder =>
                    {
                        builder.WithOrigins("http://localhost:5173") // 允许前端开发服务器地址
                               .AllowAnyMethod()                      // 允许任何HTTP方法
                               .AllowAnyHeader()                      // 允许任何请求头
                               .AllowCredentials()                    // 允许凭据
                               .WithExposedHeaders("Token-Expired");  // 暴露Token-Expired头给前端
                    });
            });

            // ========== HTTP客户端工厂 ==========
            // 添加HttpClient工厂服务，配置默认超时时间
            builder.Services.AddHttpClient("WxPayClient", client =>
            {
                client.Timeout = TimeSpan.FromSeconds(30);
                client.DefaultRequestHeaders.Add("User-Agent", "RiceShop/1.0");
            })
            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
            {
                ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true // 开发环境忽略SSL证书验证
            });
            
            // 添加通用HttpClient
            builder.Services.AddHttpClient();

            // ========== 微信配置 ==========
            // 注册微信小程序配置
            builder.Services.Configure<WxConfig>(builder.Configuration.GetSection("WxConfig"));

            // ========== Paylinks配置 ==========
            // 注册Paylinks配置
            builder.Services.Configure<PaylinksConfig>(builder.Configuration.GetSection("Paylinks"));

            // 注册Paylinks支付服务
            builder.Services.AddScoped<IPaylinksPaymentService, PaylinksPaymentService>();

            // ========== 业务服务依赖注入 ==========
            // 注册各种业务服务到依赖注入容器
            builder.Services.AddScoped<IAdminService, AdminService>();       // 管理员服务
            builder.Services.AddScoped<IRoleService, RoleService>();         // 角色服务
            builder.Services.AddScoped<IMenuService, MenuService>();         // 菜单服务
            builder.Services.AddScoped<IUserService, UserService>();         // 用户服务
            builder.Services.AddScoped<ICategoryService, CategoryService>(); // 分类服务
            builder.Services.AddScoped<IAddressService, AddressService>();   // 地址服务
            builder.Services.AddScoped<IBrandService, BrandService>();       // 品牌服务
            builder.Services.AddScoped<IGoodService, GoodService>();         // 商品服务
            builder.Services.AddScoped<IOrderService, OrderService>();       // 订单服务
            builder.Services.AddScoped<ICartService, CartService>();         // 购物车服务
            builder.Services.AddScoped<ICouponService, CouponService>();     // 优惠券服务

            // 添加HTTP上下文访问器
            builder.Services.AddHttpContextAccessor();           

            var app = builder.Build();



           

            // ========== HTTP请求管道配置 ==========

            // 开发环境下启用Swagger
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            // 启用CORS跨域支持
            app.UseCors("AllowAll");

            // 启用HTTPS重定向
            app.UseHttpsRedirection();

            // ========== 静态文件服务配置 ==========
            // 创建上传文件目录
            var uploadDir = Path.Combine(app.Environment.ContentRootPath, "upload");
            if (!Directory.Exists(uploadDir))
            {
                Directory.CreateDirectory(uploadDir);
            }

            // 配置静态文件服务选项
            var staticFileOptions = new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(uploadDir), // 文件提供程序
                RequestPath = "/upload",                            // 请求路径映射
                OnPrepareResponse = ctx =>
                {
                    // 为静态文件添加CORS头
                    ctx.Context.Response.Headers["Access-Control-Allow-Origin"] = "*";
                    ctx.Context.Response.Headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS";
                    ctx.Context.Response.Headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization, X-Requested-With";
                    ctx.Context.Response.Headers["Access-Control-Allow-Credentials"] = "true";
                    ctx.Context.Response.Headers["Access-Control-Max-Age"] = "86400";

                    // 添加安全头
                    ctx.Context.Response.Headers["X-Content-Type-Options"] = "nosniff";  // 防止MIME类型嗅探
                    ctx.Context.Response.Headers["X-Frame-Options"] = "SAMEORIGIN";      // 防止点击劫持
                    ctx.Context.Response.Headers["Cache-Control"] = "public,max-age=31536000"; // 缓存控制
                }
            };

            // 启用默认静态文件服务
            app.UseStaticFiles();
            // 启用自定义静态文件服务（上传文件）
            app.UseStaticFiles(staticFileOptions);

            // ========== 中间件管道 ==========
            app.UseAuthentication(); // 启用身份认证中间件
            app.UseAuthorization();  // 启用授权中间件
            app.MapControllers();    // 映射控制器路由



            // 启动应用程序
            app.Run();
        }
    }
}
